package gcore

import (
	"encoding/json"
	"gitee.com/lv_baobao/gcore/logHelper"
	"io/ioutil"
	"strings"
	"sync"
)

type DbConfig struct {
	ConnectionString string
	DataBaseType     string
	DataBaseKey      string
	DataBase         string
	TargetDataBase   *DbConfig
}

type RedisServer struct {
	Host string
	Port int
}

type RedisServerType int

const (
	//普通
	NormalClient RedisServerType = 0
	//哨兵
	FailoverClient RedisServerType = 1
	//集群
	Cluster RedisServerType = 2
)

type RedisConfig struct {
	ServerList []RedisServer
	PassWord   string
	KeepAlive  int
	ServerType RedisServerType
	MasterName string
	PoolSize   int
}

type RabbitMqConfig struct {
	Host               string
	Port               int
	UserName           string
	PassWord           string
	VirtualHost        string
	RequestedHeartBeat int
	PoolCount          int
}

type GlobalConfig struct {
	ServerPort      int
	ServerIp        string
	ConsulAddress   string
	AuthorityEnable bool
}

type AppSettings struct {
	NatsUrl             string
	DBConfig            []DbConfig
	Redis               RedisConfig
	RabbitMq            RabbitMqConfig
	GlobalConfig        GlobalConfig
	GateWayUrl          string
	ShowSql             bool
	DbSyncServerAddress string
	EnableSyncDb        bool
	EnableSyncRedis     bool
	AuthCode            string
}

type AppSettingsHelper struct {
}

var appSettingsHelper *AppSettingsHelper
var appSettingsHelperOnce sync.Once

func NewAppSettingsHelper() *AppSettingsHelper {
	appSettingsHelperOnce.Do(func() {
		appSettingsHelper = &AppSettingsHelper{}
	})
	return appSettingsHelper
}

var appSettings *AppSettings

func (a *AppSettingsHelper) GetAppConfig() *AppSettings {
	if appSettings != nil {
		return appSettings
	}
	var path = "config/appsettings.json"
	path = strings.ReplaceAll(path, "\\", "/")
	bytes, err := ioutil.ReadFile(path)
	if err != nil {

		logHelper.Error("GetAppConfig:", err)
		return nil
	}

	appSettings = &AppSettings{}

	err = json.Unmarshal(bytes, appSettings)
	if err != nil {
		logHelper.Error("配置文件出错,", err)
		return nil
	}
	logHelper.Info("读取配置成功:")
	return appSettings
}
